package com.zk.iotgateway.net.tcp;


import com.zk.iotgateway.util.SpringUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @Author mn
 * @Description tcp handler
 * @Date 上午 09:21 2019/7/3 0003
 * @Param
 * @return
 **/
@Component
@Scope("prototype")
public class IotTcpServerChannelInitializer extends ChannelInitializer<NioSocketChannel> {


    private long allIdleTime ;

    @Override
    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
        ChannelPipeline channelPipLine = nioSocketChannel.pipeline();
        //心跳检测,超时时间5秒，指定时间中没有读写操作会触发IdleStateEvent事件
        channelPipLine.addLast("idleStateHandler", new IdleStateHandler(0,0,allIdleTime, TimeUnit.SECONDS));
        //自定义编解码器  需要在自定义的handler的前面即pipeline链的前端,不能放在自定义handler后面，否则不起作用
        channelPipLine.addLast("codec", (ChannelHandler) SpringUtil.getBean("iotCommonCodec"));
        channelPipLine.addLast("Iothandler", (ChannelHandler) SpringUtil.getBean("iotCommonHandler"));
    }


    public long getAllIdleTime() {
        return allIdleTime;
    }

    public void setAllIdleTime(long allIdleTime) {
        this.allIdleTime = allIdleTime;
    }
}
